package org.wltea.analyzer.dic;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.SpecialPermission;
import org.wltea.analyzer.help.ESPluginLoggerFactory;

import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.sql.*;

/**
 * mysql
 *
 */
public class MySQLMonitor implements Runnable {

    /**
     * 日志
     */
    private static final Logger logger = ESPluginLoggerFactory.getLogger(MySQLMonitor.class.getName());


    private String url;

    private String user;

    private String password;

    public MySQLMonitor(String url, String user, String password) {
        this.url = url;
        this.user = user;
        this.password = password;
    }

    @Override
    public void run() {
        SpecialPermission.check();
        AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
            this.runUnprivileged();
            return null;
        });
    }

    public void runUnprivileged()  {
        Connection connection = null;
        Statement statement = null;
        try {
            connection = DriverManager.getConnection(
                    url,
                    user,
                    password);
            if (connection == null) {
                logger.error("connect failed");
                return;
            }
            statement = connection.createStatement();
            Integer reloadLogId = Dictionary.getSingleton().checkNeedReload(statement);
            if (reloadLogId != null) {
                Dictionary.getSingleton().reloadMysqlWords(statement);
            }
            Integer reloadStopWordsLogId = Dictionary.getSingleton().checkNeedReloadStopWords(statement);
            if (reloadStopWordsLogId != null) {
                Dictionary.getSingleton().reloadMysqlStopWords(statement);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally{
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
